package com.wyh.blog.aspect;


import com.wyh.blog.model.dto.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.method.annotation.HandlerMethodValidationException;

/**
 * 统一处理异常
 */

@ControllerAdvice
@RestController
@Slf4j
public class ExceptionAdvice {
    @ExceptionHandler
    public Result exceptionHandler(BlogInfoException blogInfoException){
        log.error("e: ", blogInfoException);
        return Result.fail(blogInfoException.getMsg());
//        return blogInfoException.getMsg();
    }

    @ExceptionHandler
    public Result exceptionHandler(Exception e){
        log.error("e: ", e);
        return Result.fail(e.getMessage());
    }

    @ExceptionHandler
    public Result exceptionHandler(MethodArgumentNotValidException e){
        log.error("e: ", e);
        String s = e.getBindingResult().getFieldError().getDefaultMessage().toString();
        return Result.fail(s);
    }

    @ExceptionHandler
    public Result exceptionHandler(HandlerMethodValidationException e){
        log.error("e:", e);
        String defaultMessage = e.getAllErrors().stream().findFirst().get().getDefaultMessage();
        return Result.fail(defaultMessage);
    }
}
